package com.ugoodtech.mdcc.web.service.impl;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.core.domain.QQuestionGroup;
import com.ugoodtech.mdcc.core.domain.QuestionGroup;
import com.ugoodtech.mdcc.core.domain.QuestionSection;
import com.ugoodtech.mdcc.core.repository.QuestionGroupRepository;
import com.ugoodtech.mdcc.core.repository.QuestionSectionRepository;
import com.ugoodtech.mdcc.web.service.QuestionGroupService;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

@Service
public class QuestionGroupServiceImpl implements QuestionGroupService {

    @Autowired
    private QuestionGroupRepository questionGroupRepository;

    @Autowired
    private QuestionSectionRepository questionSectionRepository;


    @Override
    public int queryQuestionGroupNum(Long sectionId) {
        Page<QuestionGroup> questionGroups=queryQuestionGroup(sectionId,new PageRequest(0,1000));
        if(null!=questionGroups.getContent()){
            return questionGroups.getContent().size();
        }else{
            return 0;
        }
    }

    @Override
    public Page<QuestionGroup> queryQuestionGroup(Long sectionId, Pageable pageable) {
        QQuestionGroup qQuestionGroup = QQuestionGroup.questionGroup;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qQuestionGroup.deleted.eq(false));
        if (null!=sectionId) {
            builder.and(qQuestionGroup.questionSection.id.eq(sectionId));
        }
        Page<QuestionGroup> questionGroups = questionGroupRepository.findAll(builder,pageable);
        return questionGroups;
    }

    @Override
    public QuestionGroup createQuestionGroup(@ApiParam("题目名称") @RequestParam String name,
                                             @ApiParam("章节Id") @RequestParam Long sectionId) {
        QuestionGroup questionGroup=new QuestionGroup();
        QuestionSection questionSection=questionSectionRepository.findOne(sectionId);
        questionGroup.setQuestionSection(questionSection);
        questionGroup.setTitle(name);
        return questionGroupRepository.save(questionGroup);
    }
}
